package org.myhibernate.core.method;

import java.sql.Connection;
import java.util.List;
import java.util.Map;

import org.myhibernate.cache.CacheContainer;
import org.myhibernate.cache.CacheContainers;
import org.myhibernate.cache.RemoveSqlCaches;
import org.myhibernate.core.method.CacheQuery;
import org.myhibernate.core.method.GenericMethod;
import org.myhibernate.db.DataHelper;


public class DeletesMethod<T> extends GenericMethod<T>
{
	private CacheQuery cacheQuery=null;
	public void init(Class cls, Connection connection) 
	{ 
		super.init(cls, connection);
		cacheQuery=new CacheQuery(connection, cls); 
	} 
	@Override
	public void init(Class cl, DataHelper helper) {
		super.init(cl, helper);
		cacheQuery=new CacheQuery(cl, helper);
	}
	@Override
	public void init(Class cl, Connection connection, DataHelper helper) {
		super.init(cl, connection, helper);
		cacheQuery=new CacheQuery(cl, connection, helper);
	}
	@Override
	public Object execute(Object list, Map map) throws Exception 
	{
		boolean flag=false;
		List<Object> idList=(List<Object>) list;
		try 
		{
			getDataHelper().getConnection().setAutoCommit(false);// not commit
			///////////////////////////////////////
			// delete from database
			for (int i = 0; i < idList.size(); i++) 
			{
				Object obj=idList.get(i);
				if (getBuffer().length()>0) {
					getBuffer().delete(0,getBuffer().length());
				}
				getBuffer().append("delete from "+getMapping().getTable()+" where "+getMapping().getId_Column()+"=");
				getBuffer().append(getHandle().handle(obj));
				String sql=getSql();
				cacheQuery.executeSql(sql);
			}
			//delete caches
			CacheContainer cacheContainer=CacheContainers.getCache(getCl());
			for (int i = 0; i < idList.size(); i++) 
			{
				Object obj=idList.get(i);
				cacheContainer.remove(obj);
			}
			
			//delete sql cache
			new RemoveSqlCaches(getCl());
			flag=true;
			////////////////////////////////////////////////
			if (getDataHelper().isCommit()) {
				getDataHelper().getConnection().commit();//commit all
			}
		} catch (Exception e) 
		{
			flag=false;
			getDataHelper().getConnection().rollback();// rollback
			e.printStackTrace();
			throw new RuntimeException(e.toString());
		}finally
		{
			if (getDataHelper().isCommit()) {
				getDataHelper().getConnection().setAutoCommit(true);// set commit true
			}
		}
		return flag;
	}
	@Override
	public void close() {
		cacheQuery.close();
	}
}
